package cn.chiship.sdk.third.storage.factory;

import cn.chiship.sdk.third.core.model.DfsDTO;
import cn.chiship.sdk.third.storage.enums.DfsClassEnum;
import cn.chiship.sdk.third.storage.enums.DfsEnum;
import cn.chiship.sdk.third.storage.FileStorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * DfsFactory工厂类,根据系统用户配置，生成及缓存对应的上传下载接口实现
 *
 * @author lj
 */
public class DfsFactory {

	private static final Logger LOGGER = LoggerFactory.getLogger(DfsFactory.class);

	/**
	 * DfsService 缓存
	 */
	private final static Map<Integer, FileStorageService> baseServiceMap = new ConcurrentHashMap<>();

	/**
	 * 获取 FileStorageService
	 * @param dfsEnum
	 * @return FileStorageService
	 */
	public static FileStorageService getFileStorageService(DfsEnum dfsEnum) {
		FileStorageService fileStorageService = baseServiceMap.get(dfsEnum.getValue());
		if (null == fileStorageService) {
			Class cls;
			try {
				cls = Class.forName(DfsClassEnum.getValue(dfsEnum.getValue()));
				Method staticMethod = cls.getDeclaredMethod("getFileStorageService");
				fileStorageService = (FileStorageService) staticMethod.invoke(cls);
				baseServiceMap.put(dfsEnum.getValue(), fileStorageService);
			}
			catch (Exception e) {
				LOGGER.error("获取文件存储服务发生异常", e);
			}
		}
		return fileStorageService;
	}

	/**
	 * 获取 FileStorageService
	 * @param dfsDTO 分布式存储配置
	 * @param dfsEnum
	 * @return FileStorageService
	 */
	public static FileStorageService getFileStorageService(DfsEnum dfsEnum, DfsDTO dfsDTO) {
		FileStorageService fileStorageService = baseServiceMap.get(dfsEnum.getValue());
		if (null == fileStorageService) {
			Class cls;
			try {
				cls = Class.forName(DfsClassEnum.getValue(dfsEnum.getValue()));
				Method staticMethod = cls.getDeclaredMethod("getFileStorageService", DfsDTO.class);
				fileStorageService = (FileStorageService) staticMethod.invoke(cls, dfsDTO);
				baseServiceMap.put(dfsEnum.getValue(), fileStorageService);
			}
			catch (Exception e) {
				LOGGER.error("获取文件存储服务发生异常", e);
			}
		}
		return fileStorageService;
	}

}
